package com.psychology.service;

import com.psychology.dto.TherapistProfileDTO;
import com.psychology.entity.Therapist;
import com.psychology.exception.BusinessException;
import com.psychology.repository.TherapistRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
@Slf4j
public class TherapistService {

    @Autowired
    private TherapistRepository therapistRepository;

    public TherapistProfileDTO getProfile() {
        // 获取当前登录的咨询师信息
        // TODO: 实现获取当前登录用户的逻辑
        Therapist therapist = getCurrentTherapist();
        return convertToDTO(therapist);
    }

    @Transactional
    public void updateProfile(TherapistProfileDTO profileDTO) {
        // 获取当前登录的咨询师
        Therapist therapist = getCurrentTherapist();

        // 更新信息
        therapist.setName(profileDTO.getName());
        therapist.setTitle(profileDTO.getTitle());
        therapist.setQualification(profileDTO.getQualification());
        therapist.setExperience(profileDTO.getExperience());
        therapist.setFields(String.join(",", profileDTO.getFields()));
        therapist.setBio(profileDTO.getBio());
        therapist.setExpertise(profileDTO.getExpertise());
        therapist.setEmail(profileDTO.getEmail());

        try {
            therapistRepository.save(therapist);
        } catch (Exception e) {
            log.error("更新咨询师信息失败", e);
            throw new BusinessException("更新失败，请稍后重试");
        }
    }

    private Therapist getCurrentTherapist() {
        // TODO: 实现获取当前登录咨询师的逻辑
        throw new BusinessException("未实现获取当前登录用户的逻辑");
    }

    private TherapistProfileDTO convertToDTO(Therapist therapist) {
        TherapistProfileDTO dto = new TherapistProfileDTO();
        dto.setName(therapist.getName());
        dto.setTitle(therapist.getTitle());
        dto.setQualification(therapist.getQualification());
        dto.setExperience(therapist.getExperience());
        dto.setFields(List.of(therapist.getFields().split(",")));
        dto.setBio(therapist.getBio());
        dto.setExpertise(therapist.getExpertise());
        dto.setPhone(therapist.getPhone());
        dto.setEmail(therapist.getEmail());
        return dto;
    }

    public List<AppointmentVO> getTodaySchedule() {
        // 获取当前登录的咨询师
        Therapist therapist = getCurrentTherapist();

        // 获取今天的日期范围
        LocalDate today = LocalDate.now();
        LocalDateTime startOfDay = today.atStartOfDay();
        LocalDateTime endOfDay = today.atTime(23, 59, 59);

        // 查询今日预约
        List<Appointment> appointments = appointmentRepository.findByTherapistAndAppointmentDateBetween(
                therapist,
                startOfDay,
                endOfDay);

        // 转换为VO
        return appointments.stream()
                .map(AppointmentVO::fromEntity)
                .collect(Collectors.toList());
    }

    @Transactional
    public void updateSchedule(ScheduleDTO scheduleDTO) {
        Therapist therapist = getCurrentTherapist();

        // 检查时间段是否已被预约
        if (isTimeSlotBooked(therapist.getId(), scheduleDTO.getDate(), scheduleDTO.getTimeSlot())) {
            throw new BusinessException("该时间段已被预约");
        }

        Schedule schedule = new Schedule();
        schedule.setTherapist(therapist);
        schedule.setDate(LocalDate.parse(scheduleDTO.getDate()));
        schedule.setTimeSlot(scheduleDTO.getTimeSlot());
        schedule.setType(scheduleDTO.getType());
        schedule.setStatus("available");

        scheduleRepository.save(schedule);
    }

    public List<ScheduleVO> getWeeklySchedule(String startDate) {
        Therapist therapist = getCurrentTherapist();
        LocalDate start = LocalDate.parse(startDate);
        LocalDate end = start.plusDays(6);

        List<Schedule> schedules = scheduleRepository.findByTherapistAndDateBetween(
                therapist, start, end);

        return schedules.stream()
                .map(ScheduleVO::fromEntity)
                .collect(Collectors.toList());
    }

    private boolean isTimeSlotBooked(Long therapistId, String date, String timeSlot) {
        return scheduleRepository.existsByTherapistIdAndDateAndTimeSlotAndStatus(
                therapistId,
                LocalDate.parse(date),
                timeSlot,
                "booked");
    }
}